document.addEventListener('DOMContentLoaded', function() {
    // API基础URL
    const API_BASE_URL = 'http://localhost:5000';

    // DOM元素
    const taskList = document.getElementById('taskList');
    const createTaskBtn = document.getElementById('createTaskBtn');
    const taskModal = document.getElementById('taskModal');
    const closeBtn = document.querySelector('.close-btn');
    const cancelBtn = document.getElementById('cancelBtn');
    const taskForm = document.getElementById('taskForm');
    const modalTitle = document.getElementById('modalTitle');
    const messageTypeSelect = document.getElementById('messageType');
    const textContentGroup = document.getElementById('textContentGroup');
    const newsContentGroup = document.getElementById('newsContentGroup');

    // 加载所有任务
    loadAllTasks();

    // 事件监听
    createTaskBtn.addEventListener('click', function() {
        openTaskModal();
    });

    closeBtn.addEventListener('click', function() {
        closeTaskModal();
    });

    cancelBtn.addEventListener('click', function() {
        closeTaskModal();
    });

    window.addEventListener('click', function(event) {
        if (event.target === taskModal) {
            closeTaskModal();
        }
    });

    messageTypeSelect.addEventListener('change', function() {
        if (this.value === 'text') {
            textContentGroup.style.display = 'block';
            newsContentGroup.style.display = 'none';
        } else {
            textContentGroup.style.display = 'none';
            newsContentGroup.style.display = 'block';
        }
    });

    taskForm.addEventListener('submit', function(event) {
        event.preventDefault();
        saveTask();
    });

    // 函数定义
    function loadAllTasks() {
        fetch(`${API_BASE_URL}/tasks`)
            .then(response => response.json())
            .then(tasks => {
                renderTaskList(tasks);
            })
            .catch(error => {
                console.error('Error loading tasks:', error);
                taskList.innerHTML = '<div class="error">加载任务失败，请重试</div>';
            });
    }

    function renderTaskList(tasks) {
        if (tasks.length === 0) {
            taskList.innerHTML = '<div class="empty">暂无任务，请创建新任务</div>';
            return;
        }

        taskList.innerHTML = '';
        tasks.forEach(task => {
            const taskCard = document.createElement('div');
            taskCard.className = 'task-card';

            // 格式化日期
            const createdDate = new Date(task.created_at).toLocaleString();
            const updatedDate = new Date(task.updated_at).toLocaleString();

            // 构建任务内容HTML
            let contentHtml = '';
            if (task.message_type === 'text') {
                contentHtml = `<p><strong>文本内容:</strong> ${escapeHtml(task.content)}</p>`;
            } else {
                try {
                    const newsItems = JSON.parse(task.content);
                    contentHtml = '<p><strong>图文内容:</strong></p>';
                    newsItems.forEach((item, index) => {
                        contentHtml += `
<div class="news-item">
    <p>${index + 1}. ${escapeHtml(item.title)}</p>
    <p>${escapeHtml(item.description)}</p>
</div>`;
                    });
                } catch (e) {
                    contentHtml = `<p><strong>图文内容:</strong> 格式无效</p>`;
                }
            }

            taskCard.innerHTML = `
                <div class="task-header">
                    <h3>${escapeHtml(task.title)} <span class="task-type-badge badge-${task.message_type}">${task.message_type === 'text' ? '文本' : '图文'}</span></h3>
                </div>
                ${contentHtml}
                <p><strong>创建时间:</strong> ${createdDate}</p>
                <p><strong>更新时间:</strong> ${updatedDate}</p>
                <p><strong>任务ID:</strong> <task-id-display>${task.task_id}</task-id-display></p>
                <div class="task-url">
                    <span class="task-url-label">发送URL:</span>
                    ${API_BASE_URL}/tasks/${task.task_id}/send
                </div>
                <div class="task-actions">
                    <button class="btn secondary-btn edit-btn" data-id="${task.task_id}">编辑</button>
                    <button class="btn secondary-btn send-btn" data-id="${task.task_id}">发送</button>
                    <button class="btn danger-btn delete-btn" data-id="${task.task_id}">删除</button>
                </div>
            `;

            taskList.appendChild(taskCard);
        });

        // 添加按钮事件监听
        document.querySelectorAll('.edit-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const taskId = this.getAttribute('data-id');
                editTask(taskId);
            });
        });

        document.querySelectorAll('.delete-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const taskId = this.getAttribute('data-id');
                if (confirm('确定要删除这个任务吗？')) {
                    deleteTask(taskId);
                }
            });
        });

        document.querySelectorAll('.send-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const taskId = this.getAttribute('data-id');
                sendTaskMessage(taskId);
            });
        });
    }

    function openTaskModal(taskId = null) {
        // 清空表单
        taskForm.reset();
        document.getElementById('taskId').value = '';

        if (taskId) {
            // 编辑任务
            modalTitle.textContent = '编辑任务';
            fetch(`${API_BASE_URL}/tasks/${taskId}`)
                .then(response => response.json())
                .then(task => {
                    document.getElementById('taskId').value = task.task_id;
                    document.getElementById('title').value = task.title;
                    document.getElementById('messageType').value = task.message_type;
                    document.getElementById('webhookUrl').value = task.webhook_url;

                    if (task.message_type === 'text') {
                        textContentGroup.style.display = 'block';
                        newsContentGroup.style.display = 'none';
                        document.getElementById('textContent').value = task.content;
                    } else {
                        textContentGroup.style.display = 'none';
                        newsContentGroup.style.display = 'block';
                        // 格式化JSON以便编辑
                        try {
                            const newsContent = JSON.parse(task.content);
                            document.getElementById('newsContent').value = JSON.stringify(newsContent, null, 2);
                        } catch (e) {
                            document.getElementById('newsContent').value = task.content;
                        }
                    }
                })
                .catch(error => {
                    console.error('Error loading task:', error);
                    alert('加载任务失败，请重试');
                    closeTaskModal();
                });
        } else {
            // 创建新任务
            modalTitle.textContent = '创建新任务';
            textContentGroup.style.display = 'block';
            newsContentGroup.style.display = 'none';
        }

        taskModal.style.display = 'block';
    }

    function closeTaskModal() {
        taskModal.style.display = 'none';
    }

    function saveTask() {
        const taskId = document.getElementById('taskId').value;
        const title = document.getElementById('title').value;
        const messageType = document.getElementById('messageType').value;
        const webhookUrl = document.getElementById('webhookUrl').value;

        let content;
        if (messageType === 'text') {
            content = document.getElementById('textContent').value;
        } else {
            content = document.getElementById('newsContent').value;
            // 验证JSON格式
            try {
                JSON.parse(content);
            } catch (e) {
                alert('图文内容必须是有效的JSON格式');
                return;
            }
        }

        const taskData = {
            title: title,
            message_type: messageType,
            content: content,
            webhook_url: webhookUrl
        };

        let url = `${API_BASE_URL}/tasks`;
        let method = 'POST';

        if (taskId) {
            url = `${API_BASE_URL}/tasks/${taskId}`;
            method = 'PUT';
        }

        fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(taskData)
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应错误');
                }
                return response.json();
            })
            .then(() => {
                closeTaskModal();
                loadAllTasks();
            })
            .catch(error => {
                console.error('Error saving task:', error);
                alert('保存任务失败，请重试');
            });
    }

    function editTask(taskId) {
        openTaskModal(taskId);
    }

    function deleteTask(taskId) {
        fetch(`${API_BASE_URL}/tasks/${taskId}`, {
            method: 'DELETE'
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应错误');
                }
                return response.json();
            })
            .then(() => {
                loadAllTasks();
            })
            .catch(error => {
                console.error('Error deleting task:', error);
                alert('删除任务失败，请重试');
            });
    }

    function sendTaskMessage(taskId) {
        fetch(`${API_BASE_URL}/tasks/${taskId}/send`, {
            method: 'POST'
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应错误');
                }
                return response.json();
            })
            .then(data => {
                alert('消息发送成功');
                console.log('Message sent result:', data);
            })
            .catch(error => {
                console.error('Error sending message:', error);
                alert('发送消息失败，请重试');
            });
    }

    // 转义HTML特殊字符
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
});